package com.gofaraway.service.export.service.biz.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.gofaraway.common.enums.OssContentTypeEnum;
import com.gofaraway.common.util.OssUtils;
import com.gofaraway.service.export.factroy.ExcelHandleFactory;
import com.gofaraway.service.export.service.AbstractExportExcelService;
import com.gofaraway.service.export.service.biz.BaseExcelServiceManage;
import com.gofaraway.service.facade.request.ExportExcelRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.Date;
import java.util.Map;

/**
 * @author ChenPeng
 * @Date 2024/5/14 17:37
 */
@Service
@Slf4j
public class BaseExcelServiceManageImpl implements BaseExcelServiceManage {

    private static final String EXCEL_EXPORT_ERROR_MSG = "上传OSS文件失败";


    @Autowired
    private OssUtils ossUtils;

    @Override
    public String exportAndUploadExcel(ExportExcelRequest request) {
        log.info("exportAndUploadExcel-> excelRequest{}", JSON.toJSONString(request));
        AbstractExportExcelService exportExcelService = ExcelHandleFactory.getExportExcelService(request.getExcelType());
        return exportAndUploadToOss(request.getQueryMap(), exportExcelService);
    }

    /**
     * 导出excel & 上传oss
     *
     * @param queryMap
     * @param exportExcelService
     * @return
     */
    private String exportAndUploadToOss(Map<String, String> queryMap, AbstractExportExcelService exportExcelService) {
        String timestamp = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN);
        File fileDir = new File("/tmp/");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String fileName = "/tmp/" + timestamp + "-easyexcel.xlsx";
        try (FileOutputStream out = new FileOutputStream(fileName)) {
            //填充输出流信息
            MutablePair<Boolean, String> easyExcelExportData = exportExcelService.easyExcelExportData(queryMap, out);
            //执行成功，上传文件
            log.info("导出成功，准备上传,map:{},pair:{}", JSON.toJSONString(queryMap), JSON.toJSONString(easyExcelExportData));
            //执行成功，上传文件
            return uploadFileToOss(easyExcelExportData, fileName);
        } catch (Exception e) {
            log.error("导出异常：{}", e.getMessage(), e);
            return EXCEL_EXPORT_ERROR_MSG;
        }
    }

    public String uploadFileToOss(MutablePair<Boolean, String> easyExcelExportData, String fileName) throws Exception {
        if (easyExcelExportData.getLeft() != null && easyExcelExportData.getLeft()) {
            try (FileInputStream in = new FileInputStream(fileName)) {
                String objectName = easyExcelExportData.getRight();
                return ossUtils.uploadOssFile(in, objectName, OssContentTypeEnum.OSS_CONTENT_TYPE_XLSX);
            } catch (FileNotFoundException e) {
                log.error("未找到文件", e);
            }
        }
        return StringUtils.EMPTY;
    }
}
